/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controlador;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Blob;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.CategoriaDB;
import model.ComentariBD;
import model.ProducteDB;
import model.PuntuacioBD;

/**
 *
 * @author sheked & nives
 */
public class ServletProductes extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        if (request.getSession(false) == null) {
            response.sendRedirect("controlador");
        }
        HttpSession sessio = request.getSession(false);

        if (request.getParameter("op") == null) {
            response.sendError(13);
        }

        RequestDispatcher reqDispatcher;
        switch(Integer.parseInt(request.getParameter("op"))) {
            case 0: //mostrar productes subcategoria
                try {
                    ProducteDB producteDB = new ProducteDB();
                    CategoriaDB categoriaDB = new CategoriaDB();
                    List<Map<String,Object>> llistat = producteDB.consultaLlista(2, request.getParameter("id"));
                    Map<String,Object> rs2 = categoriaDB.consultaSubcategoria(request.getParameter("id"));

                    //el control de productes per pagina
                    /*int length = 0;
                    if (rs.last()) {
                        length = rs.getRow();
                        rs.beforeFirst();*/
                    int numProdPag = (Integer)sessio.getAttribute("numProdPagina");
                    request.setAttribute("numPagines", Integer.valueOf(numProdPag));
                    //rs.relative(i)
                    //acabat el control de productes per pagina
                    
                    request.setAttribute("subcategoria", rs2.get("nom_subcat"));
                    request.setAttribute("subcategoriaId", rs2.get("id_subcat"));
                    rs2 = categoriaDB.consultaCategoria((String)rs2.get("id_cat"));
                    request.setAttribute("categoria", rs2.get("nom_cat"));
                    request.setAttribute("categoriaId", rs2.get("id_cat"));
                    
                    request.setAttribute("productes", llistat);

                    reqDispatcher = getServletContext().getRequestDispatcher("/productes.jsp");
                    reqDispatcher.forward(request,response);
                } catch (Exception ex) {
                    response.setContentType("text/html;charset=UTF-8");
                    PrintWriter out = response.getWriter();
                    out.println("<pre>");
                    ex.printStackTrace(out);
                    out.println("</pre>");
                    //response.sendError(14);
                }
                break;
            case 1: //mostrar productes categoria
                try {
                    ProducteDB producteDB = new ProducteDB();
                    CategoriaDB categoriaDB = new CategoriaDB();
                    List<Map<String,Object>> llista = producteDB.consultaLlista(1, request.getParameter("id"));
                    Map<String, Object> map = categoriaDB.consultaCategoria(request.getParameter("id"));
                    if (!map.isEmpty()) {
                        request.setAttribute("categoria", map.get("nom_cat"));
                        request.setAttribute("categoriaId", map.get("id_cat"));
                    }



                    int numProdPag = (Integer)sessio.getAttribute("numProdPagina");
                    request.setAttribute("numPagines", Integer.valueOf(numProdPag));


                    
                    request.setAttribute("productes", llista);
                    reqDispatcher = getServletContext().getRequestDispatcher("/productes.jsp");
                    reqDispatcher.forward(request,response);
                } catch (Exception ex) {
                    response.setContentType("text/html;charset=UTF-8");
                    PrintWriter out = response.getWriter();
                    out.println("<pre>");
                    ex.printStackTrace(out);
                    out.println("</pre>");
                    //response.sendError(14);
                }
                break;
            case 2: //mostrar la imatge del producte especificat
                try {
                    ProducteDB producteDB = new ProducteDB();
                    Blob img = producteDB.consultaImatge(Integer.parseInt(request.getParameter("id")));
                        response.setContentType("image/jpeg");
                        OutputStream o = response.getOutputStream();
                        o.write(img.getBytes(1,(int)img.length()));
                        o.flush();
                        o.close();
                } catch (Exception ex) {
                    response.sendError(15);
                }
                break;
            case 3: //mostrar el producte detallat
                try {
                    ProducteDB producteDB = new ProducteDB();
                    CategoriaDB categoriaDB = new CategoriaDB();

                    Map<String, Object> prod = producteDB.consultaProducte(Integer.parseInt(request.getParameter("id")));
                    if (!prod.isEmpty()) {
                        Map<String, Object> subcat = categoriaDB.consultaSubcategoria((String)prod.get("id_subcat"));
                        if (subcat != null && !subcat.isEmpty()) {
                            request.setAttribute("subcategoria", subcat.get("nom_subcat"));
                            request.setAttribute("subcategoriaId", subcat.get("id_subcat"));
                        }
                        subcat = categoriaDB.consultaCategoria((String)prod.get("id_cat"));
                        if (subcat != null && !subcat.isEmpty()) {
                            request.setAttribute("categoria", subcat.get("nom_cat"));
                            request.setAttribute("categoriaId", subcat.get("id_cat"));
                        }
                        request.setAttribute("producteId", request.getParameter("id"));
                        request.setAttribute("producteNom", prod.get("nom"));
                    }
                    request.setAttribute("producte", prod);
                    request.setAttribute("idProducte", request.getParameter("id"));
                    ComentariBD comentaribd = new ComentariBD();
                    List<Map<String, Object>> rsC = comentaribd.consultaComentari(Integer.parseInt(request.getParameter("id")));
                    request.setAttribute("comentaris", rsC);
                    PuntuacioBD puntbd = new PuntuacioBD();
                    float rsPunt = puntbd.consultaPuntuacio(Integer.parseInt(request.getParameter("id")));
                    request.setAttribute("puntuacio", Float.valueOf(rsPunt));
                    if (sessio.getAttribute("id")!= null) {
                        request.setAttribute("puntEscollit", Integer.valueOf(puntbd.consultaPuntuacio((Integer)sessio.getAttribute("id"), Integer.parseInt(request.getParameter("id")))));
                    } else {
                        request.setAttribute("puntEscollit", Integer.valueOf(-1));
                    }
                    reqDispatcher = getServletContext().getRequestDispatcher("/prodDetall.jsp");
                    reqDispatcher.forward(request,response);
                } catch (Exception ex) {
                    response.setContentType("text/html;charset=UTF-8");
                    PrintWriter out = response.getWriter();
                    out.println("<pre>");
                    ex.printStackTrace(out);
                    out.println("</pre>");
                    //response.sendError(18);
                }
                break;
            case 4: //Enviar comentaris.
                try {
                    int id_prod = Integer.parseInt(request.getParameter("id_prod"));
                    String comentari = request.getParameter("comentari");
                    int id_client = ((Integer)sessio.getAttribute("id"));
                    ComentariBD comDB= new ComentariBD();
                    boolean ok = comDB.introdueixComentari( id_prod, comentari, id_client);
                    if (!ok) {
                        response.sendError(16);
                    }
                    ComentariBD comentaribd = new ComentariBD();
                    List<Map<String, Object>> rsC = comentaribd.consultaComentari(id_prod);
                    request.setAttribute("comentaris", rsC);
                    reqDispatcher = getServletContext().getRequestDispatcher("/commentProd.jsp");
                    reqDispatcher.forward(request,response);
                } catch (Exception e){
                    response.sendError(16);
                }
                break;
            case 5: //carregar comentaris
                try {
                    ComentariBD comentaribd = new ComentariBD();
                    List<Map<String, Object>> rsC = comentaribd.consultaComentari(Integer.parseInt(request.getParameter("id_prod")));
                    request.setAttribute("comentaris", rsC);
                    reqDispatcher = getServletContext().getRequestDispatcher("/commentProd.jsp");
                    reqDispatcher.forward(request,response);
                } catch (Exception e){
                    response.sendError(17);
                }
                break;
            case 6: //Enviar Puntuacio
                try {
                    int id_prod = Integer.parseInt(request.getParameter("id"));
                    int punt = Integer.parseInt(request.getParameter("punt"));
                    PuntuacioBD puntDB= new PuntuacioBD();
                    boolean ok = puntDB.introdueixPuntuacio(id_prod, punt, (Integer) sessio.getAttribute("id"));
                    if (!ok) {
                        response.sendError(19);
                    } else {
                        float rsPunt = puntDB.consultaPuntuacio(Integer.parseInt(request.getParameter("id")));
                        request.setAttribute("puntuacio", Float.valueOf(rsPunt));
                        request.setAttribute("puntEscollit", Integer.valueOf(punt));
                        reqDispatcher = getServletContext().getRequestDispatcher("/puntuacioProd.jsp");
                        reqDispatcher.forward(request,response);
                    }
                } catch (Exception e){
                    response.setContentType("text/html;charset=UTF-8");
                    PrintWriter out = response.getWriter();
                    out.println("<pre>");
                    e.printStackTrace(out);
                    out.println("</pre>");
                    //response.sendError(19);
                }
                break;
            case 7: //pagina principal de la botiga
                reqDispatcher = getServletContext().getRequestDispatcher("/pagePrincipal.jsp");
                reqDispatcher.forward(request,response);
                break;
            case 8: //mostrar puntuacio
                try {
                    PuntuacioBD puntbd = new PuntuacioBD();
                    float rsPunt = puntbd.consultaPuntuacio(Integer.parseInt(request.getParameter("id")));
                    request.setAttribute("puntuacio", Float.valueOf(rsPunt));
                    if (sessio.getAttribute("id")!= null) {
                        request.setAttribute("puntEscollit", Integer.valueOf(puntbd.consultaPuntuacio((Integer)sessio.getAttribute("id"), Integer.parseInt(request.getParameter("id")))));
                    } else {
                        request.setAttribute("puntEscollit", Integer.valueOf(-1));
                    }
                    reqDispatcher = getServletContext().getRequestDispatcher("/puntuacioProd.jsp");
                    reqDispatcher.forward(request,response);
                } catch (Exception e){
                    response.setContentType("text/html;charset=UTF-8");
                    PrintWriter out = response.getWriter();
                    out.println("<pre>");
                    e.printStackTrace(out);
                    out.println("</pre>");
                    //response.sendError(19);
                }
                break;
            default:
                response.sendError(2);
                break;
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
